﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace HZY.Admin.Services
{
    using System.Threading.Tasks;
    using HZY.EFCore.Repository;
    using HZY.Models;
    using HZY.Models.Sys;
    using HZY.Toolkits;
    using HZY.EFCore.Base;
    using HZY.Admin.Services.Core;
    using HZY.EFCore;
    using Microsoft.EntityFrameworkCore;

    public class DeviceService : ServiceBase<Device>
    {
        private readonly DefaultRepository<Terminal> terminalDb;
        private readonly DefaultRepository<DeviceType> deviceTypeDb;
        public DeviceService(EFCoreContext _db, DefaultRepository<Terminal> terminalDb, DefaultRepository<DeviceType> deviceTypeDb)
            : base(_db)
        {
            this.terminalDb = terminalDb;
            this.deviceTypeDb = deviceTypeDb;
        }

        #region CURD 基础

        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="Page"></param>
        /// <param name="Rows"></param>
        /// <param name="Search"></param>
        /// <returns></returns>
        public async Task<TableViewModel> FindListAsync(int Page, int Rows, Device Search)
        {
            var query = (
                from device in this.db.Devices
                from deviceType in this.db.DeviceTypes.Where(w => w.DeviceType_ID == device.Device_DeviceTypeID).DefaultIfEmpty()
                from terminal in this.db.Terminals.Where(w => w.Terminal_ID == device.Device_TerminalID).DefaultIfEmpty()
                select new { device, deviceType, terminal }
                )
                .WhereIF(w => w.device.Device_DtuID.Contains(Search.Device_DtuID), !string.IsNullOrWhiteSpace(Search?.Device_DtuID))
                .OrderByDescending(w => w.device.Device_CreateTime)
                .Select(w => new
                {
                    w.device.Device_DtuID,
                    w.deviceType.DeviceType_Name,
                    w.terminal.Terminal_Name,
                    w.device.Device_OnlineStatus,
                    w.device.Device_CreateTime,
                    _ukid = w.device.Device_ID
                })
                ;

            return await this.db.AsTableViewModelAsync(query, Page, Rows, typeof(Device), typeof(DeviceType), typeof(Terminal));
        }

        /// <summary>
        /// 新增\修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Guid> SaveAsync(Device model)
        {
            await this.InsertOrUpdateAsync(model);

            return model.Device_ID;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(List<Guid> Ids)
            => await this.DeleteAsync(w => Ids.Contains(w.Device_ID));

        /// <summary>
        /// 加载表单 数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<Dictionary<string, object>> LoadFormAsync(Guid Id)
        {
            var res = new Dictionary<string, object>();

            var Model = await this.FindByIdAsync(Id);
            var terminals = await this.terminalDb.Query().OrderBy(w => w.Terminal_Num).ToListAsync();
            var deviceTypes = await this.deviceTypeDb.Query().OrderBy(w => w.DeviceType_Num).ToListAsync();

            res[nameof(Id)] = Id;
            res[nameof(Model)] = Model.NullSafe();
            res[nameof(terminals)] = terminals;
            res[nameof(deviceTypes)] = deviceTypes;

            return res;
        }


        #endregion

        /// <summary>
        /// 根据 设备 id 集合 改变所属终端
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ChangeTerminalByDeviceIds(List<Guid> deviceIds, Guid terminalId)
        {
            var count = await this.BatchUpdateAsync(set => new Device
            {
                Device_TerminalID = terminalId

            }, w => deviceIds.Contains(w.Device_ID));

            return count > 0;
        }




    }
}
